package com.exchange.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exchange.user.dao.SysUserDao;
import com.exchange.user.dto.SelUserDto;
import com.exchange.user.dto.UserLoginDto;
import com.exchange.user.entity.SysUser;
import com.exchange.user.service.SysUserService;
import com.exchange.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/***
 *                    .::::.
 *                  .::::::::.
 *                 :::::::::::
 *             ..:::::::::::'
 *           '::::::::::::'
 *             .::::::::::
 *        '::::::::::::::..
 *             ..::::::::::::.
 *           ``::::::::::::::::
 *            ::::``:::::::::'        .:::.
 *           ::::'   ':::::'       .::::::::.
 *         .::::'      ::::     .:::::::'::::.
 *        .:::'       :::::  .:::::::::' ':::::.
 *       .::'        :::::.:::::::::'      ':::::.
 *      .::'         ::::::::::::::'         ``::::.
 *  ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 *                    '.:::::'                    ':'````..
 *
 * @Author liuhai
 * @Date 2020-11-02 16:58:43
 * @Description 用户管理接口实现类
 */
@Component
@RefreshScope
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${params.redis.effectiveTime}")
    private Integer effectiveTime;

    @Override
    public IPage<SysUser> getPageList(SelUserDto selUserDto) {
        long current = selUserDto.getCurrent() == 0 ? 1 : selUserDto.getCurrent();
        long pageSize = selUserDto.getPageSize() == 0 ? 10 : selUserDto.getPageSize();
        return this.baseMapper.getPageList(new Page<>(current, pageSize), selUserDto);
    }

    @Override
    public String userLogin(UserLoginDto userLoginDto) {
        QueryWrapper<SysUser> queryUser = new QueryWrapper<>();
        queryUser.eq("user_name", userLoginDto.getUserName());
        queryUser.eq("password", userLoginDto.getPassword());
        SysUser user = sysUserDao.selectOne(queryUser);
        if(null != user){
            String tokenValue = null;
            SysUser sysUser = null;
            if(null != user.getTokenValue()){
                sysUser = this.getUserByToken(user.getTokenValue());
            }
            if(null == sysUser){
                tokenValue = StringUtil.getUuid32();
                // 更新 tokenValue
                user.setTokenValue(tokenValue);
                this.uptUser(user);
                // 存储或更新用户信息到 redis
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                // 用 SysUser 转成 String 字符串存储，设定有效时间 ops.set(key, value, 时间长度, 时间单位);
                ops.set(tokenValue, JSON.toJSONString(user), effectiveTime, TimeUnit.HOURS);
            }else {
                tokenValue = user.getTokenValue();
            }
            return tokenValue;
        }
        return null;
    }

    @Override
    public SysUser getUserByToken(String token) {
        // 根据 key 从 redis 获取信息
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String userStr = ops.get(token);
        if(!StringUtils.isEmpty(userStr)){
            // 将 String 字符串转成 SysUser 对象
            return JSON.parseObject(userStr, SysUser.class);
        }
        return null;
    }

    @Override
    public SysUser getUserById(Integer userId) {
        return this.baseMapper.selectById(userId);
    }

    @Override
    public int uptUser(SysUser sysUser) {
        return sysUserDao.updateById(sysUser);
    }
}
